import pygame
from pygame.sprite import Sprite, Group
import queue
import threading
from web import mainThread
from libs import header_has_guuid
import os, time, math, random


# 定义窗口大小
SCREEN_WIDTH, SCREEN_HEIGHT = 1400, 687
# 外边距 左上右下
MARGINS = (100, 100, 100, 100)
BLOCK = (80, 80)
# 定义预设颜色
BLACK = pygame.Color(0, 0, 0)
WHITE = pygame.Color(255, 255, 255)
RED = pygame.Color(255, 0, 0)
GREEN = pygame.Color(0, 255, 0)
BLUE = pygame.Color(0, 0, 255)
# 定义地形颜色
maps = [
    pygame.Color(192, 192, 192),  # 0 禁用地形
    pygame.Color(0, 153, 102),  # 1 草地
    pygame.Color(204, 153, 153),
    pygame.Color(0, 0, 153),
]
# 定义系统参数
cfg = {"act": None, "menu": None, "input": []}
tcp = {"recv": queue.Queue(), "send": queue.Queue()}
part = []
TRACKS = [97 + 60, 197 + 60, 297 + 60, 397 + 60, 497 + 60]
ROWS = [250, 350, 450, 550, 650, 750, 850, 950, 1050]
HERO = os.listdir("hero")
NAMES = [
    "￡轻唱ㄣ人生彡",
    "ˇ余生ˉ残浮‖",
    "￡守望战神ぃ",
    "雙漁蓙﹏誣語",
    "浅兮丶青柠",
    "垨护乄缃垨",
    "￡Hero滴答滴﹋",
    "躺ㄕ③百渞",
    "◆▁演绎、未来",
    "浮城之心 ゆ",
    "堕落↙完美",
    "蓝调☆旋律",
    "落ㄖ傾城﹏",
    "陌路、夜未央",
    "往事携冷风",
]
# 定义僵尸合集
ALLZOMBIE = [
    {
        "name": "NormalZombie",
        "default": "Zombie",
        "ack": "ZombieAttack",
        "head": "ZombieHead",
        "losthead": "ZombieLostHead",
        "lostack": "ZombieLostHeadAttack",
        "die": "ZombieDie",
        "boom": "BoomDie",
        "note": "小僵尸",
    },
    # {
    #     "name": "NewspaperZombie",
    #     "default": "NewspaperZombie",
    #     "ack": "NewspaperZombieAttack",
    #     "losthead": "NewspaperZombieLostHead",
    #     "lostack": "NewspaperZombieLostHeadAttack",
    #     "nopaper": "NewspaperZombieNoPaper",
    #     "paperack": "NewspaperZombieNoPaperAttack",
    #     "die": "NewspaperZombieDie",
    #     "note": "报纸僵尸",
    # },
    {
        "name": "FlagZombie",
        "default": "FlagZombie",
        "ack": "FlagZombieAttack",
        "losthead": "FlagZombieLostHead",
        "lostack": "FlagZombieLostHeadAttack",
        "note": "旗帜僵尸",
    },
    {
        "name": "ConeheadZombie",
        "default": "ConeheadZombie",
        "ack": "ConeheadZombieAttack",
        "note": "交通锥僵尸",
    },
    {
        "name": "BucketheadZombie",
        "default": "BucketheadZombie",
        "ack": "BucketheadZombieAttack",
        "note": "铁桶僵尸",
    },
]


def findRowst(target):
    """查找最接近的数"""
    closest = ROWS[0]
    diff = abs(closest - target)

    for num in ROWS:
        if abs(num - target) < diff:
            closest = num
            diff = abs(num - target)

    return closest


def findClosest(target):
    """查找最接近的数"""
    closest = TRACKS[0]
    diff = abs(closest - target)

    for num in TRACKS:
        if abs(num - target) < diff:
            closest = num
            diff = abs(num - target)

    return closest


class Baseitem(Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)


class myCards(Baseitem):  # 卡片类
    plants = [
        "SunFlower",  # 0 太阳花
        "Peashooter",  # 1 豌豆射手
        "Chomper",  # 2 食人花
        "WallNut",  # 3 土豆
        "CherryBomb",  # 4 樱桃
        "SnowPea",  # 5 寒冰
        "Threepeater",  # 6 3豌豆
        "PotatoMine",
        "HypnoShroom",
        "IceShroom",
        "Jalapeno",
        "PuffShroom",
        "RepeaterPea",
        "ScaredyShroom",
        "Spikeweed",
        "Squash",
        "Sun",
        "SunShroom",
    ]
    prices = [50, 100, 150, 50, 150, 175, 325]

    def __init__(self, left, top, index):
        super(myCards, self).__init__()
        self.name = self.plants[index]
        self.guid = header_has_guuid()
        self.price = self.prices[index]
        self.mode = "card"  # 物理类别
        self.status = "fight"
        image = pygame.image.load(f"graphics/Cards/{index}.png")
        self.image = pygame.transform.scale(image, (50, 60))
        self.rect = self.image.get_rect()  # 根据图片获取区域
        self.rect.left, self.rect.top = left, top
        self.dragging = False  # 正在拖动
        # 副本
        try:
            self.copy = pygame.image.load(
                f"graphics/Plants/{self.plants[index]}/{self.plants[index]}_0.png"
            )
        except:
            self.copy = pygame.image.load(
                f"graphics/Plants/{self.plants[index]}/{self.plants[index]}/{self.plants[index]}_0.png"
            )
        self.move_rect = self.copy.get_rect()

    def displayTank(self):
        # 调用blit展示
        MainGame.window.blit(self.image, self.rect)

    def targetBlock(self, pos):
        """计算目标位置块"""
        # x, y = math.ceil((pos[0] - 100) / 80) - 1, math.ceil((pos[1] - 100) / 80) - 1
        # if x < 0 or x > 12:
        #     return
        # if y < 0 or y > 6:
        #     return
        # track = thread2.findMapsFromGuidState(y)
        # if not track:
        #     return
        # print("创建位置: ", pos, self.name, self.guid)
        data = {
            "act": "newPlant",
            "guid": thread2.guid,
            "data": {
                "name": self.name,
                "guid": self.guid,
                "point": pos,
                "price": self.price,
            },
        }
        tcp["send"].put(data)

    def handle_event(self, event):
        if event.type == pygame.MOUSEBUTTONDOWN:
            if self.rect.collidepoint(*pygame.mouse.get_pos()):
                self.dragging = True
        elif event.type == pygame.MOUSEBUTTONUP:
            if self.dragging:
                self.targetBlock(event.pos)
            self.dragging = False
            # print("释放位置:", event.pos)
        elif event.type == pygame.MOUSEMOTION:
            if self.dragging:
                self.move_rect.center = event.pos


# print(os.listdir("graphics/Plants"))


class myItems(Baseitem):  # 商城类
    def __init__(self, left, top):
        super(myItems, self).__init__()
        self.mode = "items"  # 物理类别
        self.status = "fight"
        self.image = pygame.image.load("graphics/Screen/ChooserBackground.png")
        self.rect = self.image.get_rect()  # 根据图片获取区域
        self.rect.left, self.rect.top = left, top

    def displayTank(self):
        # 调用blit展示
        MainGame.window.blit(self.image, self.rect)


class myHeros(Baseitem):  # 队友类
    def __init__(self, left, top):
        super(myHeros, self).__init__()
        self.mode = "hero"  # 物理类别
        self.status = "fight"
        image = pygame.image.load(f"hero/{random.choice(HERO)}")
        self.image = pygame.transform.scale(image, (70, 87))
        self.rect = self.image.get_rect()  # 根据图片获取区域
        self.rect.left, self.rect.top = left, top

    def displayTank(self):
        # 调用blit展示
        MainGame.window.blit(self.image, self.rect)

    def setData(self, data):
        """设置数据"""


class myTracks(Baseitem):  # 地图类
    def __init__(self, left, top):
        super(myTracks, self).__init__()
        self.mode = "track"
        self.status = "fight"
        # self.image = pygame.Surface([80, 80])
        # self.image.fill(GREEN)
        self.image = pygame.image.load(f"graphics/Items/Background/Background_0.jpg")
        self.rect = self.image.get_rect()  # 根据图片获取区域
        self.rect.left, self.rect.top = left, top

    def displayTank(self):
        # 调用blit展示
        MainGame.window.blit(self.image, self.rect)


# -----------------------------------------------------------------
# 僵尸类
# -----------------------------------------------------------------
class allZombie(Baseitem):  # 基础僵尸类
    def __init__(self):
        super(allZombie, self).__init__()
        self.move = "graphics/Zombies/NormalZombie/Zombie"
        self.image = pygame.image.load(f"{self.move}/Zombie_0.png")
        self.rect = self.image.get_rect()  # 根据图片获取区域
        # self.rect.left, self.rect.top = left, top
        # self.rect.left, self.rect.top = 1200, 100 * 0 + 0 + 97

        self.hp = 100
        self.ack = 10
        self.speed = 2

    def displayTank(self):
        # 调用blit展示
        MainGame.window.blit(self.image, self.rect)

    def startMove(self):
        thread = threading.Thread(target=self.doMove)
        thread.daemon = True
        thread.start()

    def doMove(self):
        """移动线程"""
        idx = len(os.listdir(self.move))
        while self.hp > 0:
            time.sleep(0.1)
            for i in os.listdir(self.move):  # 动画
                self.image = pygame.image.load(f"{self.move}/{i}")
                self.rect.left -= 2
                time.sleep(0.1)


class NormalZombie(allZombie):  # 普通僵尸类
    def __init__(self, data):
        super(NormalZombie, self).__init__()
        self.move = "graphics/Zombies/NormalZombie/Zombie"
        self.attack = "graphics/Zombies/NormalZombie/ZombieAttack"

        self.losthead = "graphics/Zombies/NormalZombie/ZombieLostHead"
        self.lostheadact = "graphics/Zombies/NormalZombie/ZombieLostHeadAttack"

        self.image = pygame.image.load(f"{self.move}/Zombie_0.png")
        self.rect = self.image.get_rect()  # 根据图片获取区域
        # self.rect.left, self.rect.top = left, top

        self.guid = data.get("guid")
        self.track = data.get("tract")
        self.rect.left, self.rect.top = 1200, 100 * (self.track) + 0 + 97

        self.hp = 100
        self.speed = 2

    def ZombieHead(self):
        """掉头"""
        path = "graphics/Zombies/NormalZombie/ZombieHead"
        for i in os.listdir(path):
            self.image = pygame.image.load(f"{path}/{i}")
            time.sleep(0.1)

    def ZombieDie(self):
        """无头死亡"""
        path = "graphics/Zombies/NormalZombie/ZombieDie"
        for i in os.listdir(path):
            self.image = pygame.image.load(f"{path}/{i}")
            time.sleep(0.1)

    def BoomDie(self):
        """炸死"""
        path = "graphics/Zombies/NormalZombie/BoomDie"
        for i in os.listdir(path):
            self.image = pygame.image.load(f"{path}/{i}")
            time.sleep(0.1)


class FlagZombie(allZombie):  # 旗帜僵尸类
    def __init__(self, data):
        super(FlagZombie, self).__init__()
        self.move = "graphics/Zombies/FlagZombie/FlagZombie"
        self.attack = "graphics/Zombies/FlagZombie/FlagZombieAttack"

        self.losthead = "graphics/Zombies/FlagZombie/FlagZombieLostHead"
        self.lostheadact = "graphics/Zombies/FlagZombie/FlagZombieLostHeadAttack"

        self.image = pygame.image.load(f"{self.move}/FlagZombie_0.png")
        self.rect = self.image.get_rect()  # 根据图片获取区域
        # self.rect.left, self.rect.top = left, top

        self.guid = data.get("guid")
        self.track = data.get("tract")
        self.rect.left, self.rect.top = 1200, 100 * (self.track) + 0 + 97

        self.hp = 100
        self.speed = 3


class ConeheadZombie(allZombie):  # 交通锥僵尸类
    def __init__(self, data):
        super(ConeheadZombie, self).__init__()
        self.move = "graphics/Zombies/ConeheadZombie/ConeheadZombie"
        self.attack = "graphics/Zombies/ConeheadZombie/ConeheadZombieAttack"

        self.image = pygame.image.load(f"{self.move}/ConeheadZombie_0.png")
        self.rect = self.image.get_rect()  # 根据图片获取区域
        # self.rect.left, self.rect.top = left, top

        self.guid = data.get("guid")
        self.track = data.get("tract")
        self.rect.left, self.rect.top = 1200, 100 * (self.track) + 0 + 97

        self.hp = 200
        self.speed = 2


class BucketheadZombie(allZombie):  # 铁通僵尸类
    def __init__(self, data):
        super(BucketheadZombie, self).__init__()
        self.move = "graphics/Zombies/BucketheadZombie/BucketheadZombie"
        self.attack = "graphics/Zombies/BucketheadZombie/BucketheadZombieAttack"

        self.image = pygame.image.load(f"{self.move}/BucketheadZombie_0.png")
        self.rect = self.image.get_rect()  # 根据图片获取区域
        # self.rect.left, self.rect.top = left, top

        self.guid = data.get("guid")
        self.track = data.get("tract")
        self.rect.left, self.rect.top = 1200, 100 * (self.track) + 0 + 97

        self.hp = 300
        self.speed = 2


# -----------------------------------------------------------------
# 植物类
# -----------------------------------------------------------------
class allPlant(Baseitem):  # 基础植物类
    def __init__(self):
        super(allPlant, self).__init__()
        self.move = "graphics/Zombies/NormalZombie/Zombie"
        self.image = pygame.image.load(f"{self.move}/Zombie_0.png")
        self.rect = self.image.get_rect()  # 根据图片获取区域

        self.hp = 100
        self.ack = 10

    def displayTank(self):
        # 调用blit展示
        MainGame.window.blit(self.image, self.rect)

    def setData(self, data):
        """设置数据"""
        point = data.get("point")
        self.rect.left, self.rect.top = findRowst(point[0]), findClosest(point[1])

    def startMove(self):
        thread = threading.Thread(target=self.doMove)
        thread.daemon = True
        thread.start()

    def doMove(self):
        """移动线程"""
        idx = len(os.listdir(self.move))
        while self.hp > 0:
            time.sleep(0.1)
            for i in os.listdir(self.move):  # 动画
                self.image = pygame.image.load(f"{self.move}/{i}")
                time.sleep(0.1)


class SunFlower(allPlant):  # 0 太阳花
    def __init__(self):
        super(SunFlower, self).__init__()
        self.move = "graphics/Plants/SunFlower"
        self.image = pygame.image.load(f"{self.move}/SunFlower_0.png")
        self.rect = self.image.get_rect()  # 根据图片获取区域

        self.hp = 100
        self.ack = 10


class Peashooter(allPlant):  # 1 豌豆射手
    def __init__(self):
        super(Peashooter, self).__init__()
        self.move = "graphics/Plants/Peashooter"
        self.image = pygame.image.load(f"{self.move}/Peashooter_0.png")
        self.rect = self.image.get_rect()  # 根据图片获取区域

        self.hp = 100
        self.ack = 10


class Chomper(allPlant):  # 2 食人花
    def __init__(self):
        super(Chomper, self).__init__()
        self.move = "graphics/Plants/Chomper/Chomper"
        self.image = pygame.image.load(f"{self.move}/Chomper_0.png")
        self.rect = self.image.get_rect()  # 根据图片获取区域

        self.hp = 100
        self.ack = 10


class WallNut(allPlant):  # 3 土豆
    def __init__(self):
        super(WallNut, self).__init__()
        self.move = "graphics/Plants/WallNut/WallNut"
        self.image = pygame.image.load(f"{self.move}/WallNut_0.png")
        self.rect = self.image.get_rect()  # 根据图片获取区域

        self.hp = 100
        self.ack = 10


class CherryBomb(allPlant):  # 4 樱桃
    def __init__(self):
        super(CherryBomb, self).__init__()
        self.move = "graphics/Plants/CherryBomb"
        self.image = pygame.image.load(f"{self.move}/CherryBomb_0.png")
        self.rect = self.image.get_rect()  # 根据图片获取区域

        self.hp = 100
        self.ack = 10


class SnowPea(allPlant):  # 5 寒冰
    def __init__(self):
        super(SnowPea, self).__init__()
        self.move = "graphics/Plants/SnowPea"
        self.image = pygame.image.load(f"{self.move}/SnowPea_0.png")
        self.rect = self.image.get_rect()  # 根据图片获取区域

        self.hp = 100
        self.ack = 10


class Threepeater(allPlant):  # 6 豌豆*3
    def __init__(self):
        super(Threepeater, self).__init__()
        self.move = "graphics/Plants/Threepeater"
        self.image = pygame.image.load(f"{self.move}/Threepeater_0.png")
        self.rect = self.image.get_rect()  # 根据图片获取区域

        self.hp = 100
        self.ack = 10


# -----------------------------------------------------------------
class MainGame:
    window = None

    def __init__(self):
        self.isRun = True  # 运行状态
        self.guid = ""
        self.name = ""
        self.status = "wait"  # 游戏状态
        self.money = 0
        self.level = 0

        self.tracks = Group()
        self.cards = Group()
        self.heros = Group()
        self.zombies = Group()
        self.plants = Group()
        self.myShop = Group()

    def stop(self):
        self.isRun = False

    def startGame(self):
        pygame.display.init()  # 加载主窗口
        MainGame.window = pygame.display.set_mode(
            [SCREEN_WIDTH, SCREEN_HEIGHT]
        )  # 设置窗口大小并显示
        pygame.font.init()  # 初始化文本
        # 窗口标题设置
        pygame.display.set_caption("植物大战僵尸")
        # 关闭输入法
        pygame.key.stop_text_input()

        while self.isRun:
            time.sleep(0.1)
            # 颜色填充
            MainGame.window.fill(BLACK)
            # 绘制地形
            for track in self.tracks:
                track.displayTank()
            # 绘制队友
            for hero in self.heros:
                hero.displayTank()
            # 绘制卡片
            for card in self.cards:
                card.displayTank()
            # 绘制植物
            for plant in self.plants:
                plant.displayTank()
            # 绘制僵尸
            for zombie in self.zombies:
                zombie.displayTank()
            # 绘制当前金币
            MainGame.window.blit(self.getTextSuface(str(self.money), BLACK), (25, 63))
            # 获取事件
            self.getEvent()
            # 获取网络
            self.getSocket()
            # 绘制队友
            # for surface, pos in self.messageGroup():
            #     MainGame.window.blit(surface, pos)
            # 绘制菜单文字
            for surface, pos in self.messageShow():
                MainGame.window.blit(surface, pos)
            # 更新视图
            pygame.display.update()
        print("...游戏结束...")

    def getTextSuface(self, text, color):
        """显示单行文本"""
        # pygame.font.init()  # 字体初始化
        font = pygame.font.SysFont("kaiti", 18)
        textSurface = font.render(text, True, color)
        return textSurface

    def messageGroup(self):
        """显示队友状态"""
        if not part:
            return {}
        font = pygame.font.SysFont("SimSun", 16)
        text_surfaces = [
            font.render(f'{line["status"]} {line["name"]}', True, (0, 0, 255))
            for line in part
        ]
        text_positions = [
            (SCREEN_WIDTH - 200 - 5, 10 + i * (text_surfaces[0].get_height() + 5))
            for i, _ in enumerate(part)
        ]
        return zip(text_surfaces, text_positions)

    def messageShow(self):
        """显示文本"""
        textlist = cfg.get("menu", [])
        if not textlist:
            return {}
        font = pygame.font.SysFont("SimSun", 20)
        text_surfaces = [font.render(line, True, (0, 255, 0)) for line in textlist]
        text_positions = [
            (5, 400 + i * (text_surfaces[0].get_height() + 5))
            for i, _ in enumerate(textlist)
        ]
        return zip(text_surfaces, text_positions)

    def getEvent(self):
        """获取所有事件"""
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                # 退出游戏
                self.stop()
            elif event.type == pygame.KEYUP:
                idx = 0 - (48 - event.key)
                if cfg["act"] == "room" and idx in cfg["input"]:
                    index = eval(cfg["menu"][idx].split("->")[1])["index"]
                    print(idx, index)
                    tcp["send"].put({"act": "enter", "guid": self.guid, "data": index})
                elif cfg["act"] == "enter" and idx in cfg["input"]:
                    if idx == 1:
                        tcp["send"].put(
                            {
                                "act": "name",
                                "guid": self.guid,
                                "data": random.choice(NAMES),
                            }
                        )
                elif cfg["act"] == "wait" and idx in cfg["input"]:
                    if idx == 1:
                        tcp["send"].put({"act": "ready", "guid": self.guid, "data": 1})
                    elif idx == 9:
                        tcp["send"].put({"act": "quit", "guid": self.guid, "data": ""})
                elif cfg["act"] == "ready" and idx in cfg["input"]:
                    if idx == 1:
                        tcp["send"].put({"act": "wait", "guid": self.guid, "data": 1})
            else:
                for sprite in self.cards:
                    sprite.handle_event(event)

    def getSocket(self):
        """获取网络消息"""
        while not tcp["recv"].empty():
            event = tcp["recv"].get()
            print("网络消息: ", event)
            if event.get("act") == "init":
                if not event.get("code") == 200:
                    return
                self.guid = event.get("guid")
                cfg["act"] = "init"
                cfg["menu"] = [event.get("data")]
                tcp["send"].put({"act": "room", "guid": self.guid, "data": 1})

            elif event.get("act") == "room":
                if not event.get("code") == 200:
                    return
                obj = event.get("data")
                for i in obj.get("data"):
                    cfg["act"] = "room"
                    cfg["menu"].append(f'{len(cfg["input"]) + 1} -> {i}')
                    cfg["input"].append(len(cfg["input"]) + 1)
                if len(cfg["menu"]) - 1 < obj.get("count"):
                    tcp["send"].put(
                        {
                            "act": "room",
                            "guid": self.guid,
                            "data": obj.get("page") + 1,
                        }
                    )
            elif event.get("act") == "name":
                if not event.get("code") == 200:
                    return
                if event.get("guid") == self.guid:
                    # 队友改名
                    self.name = event.get("data")
                    cfg["act"] = "wait"
                    cfg["menu"] = ["1 准备就绪", "9 离开房间"]
                    cfg["input"] = [1, 9]
                else:
                    p = self.findPartsFromGuid(event.get("guid"))
                    if not p:
                        return
                    p["name"] = event.get("data")
            elif event.get("act") == "enter":
                if not event.get("code") == 200:
                    return
                if not event.get("guid") == self.guid:
                    # 队友进入房间
                    part.append(
                        {"guid": event.get("guid"), "name": "", "status": "wait"}
                    )
                else:
                    for i in event.get("data"):
                        if i.get("guid") == self.guid:
                            continue
                        part.append(
                            {"guid": i.get("guid"), "name": "", "status": "wait"}
                        )
                    cfg["act"] = "enter"
                    cfg["menu"] = ["1 修改随机昵称", "9 离开房间"]
                    cfg["input"] = [1, 9]
                    # 直接设置昵称
                    tcp["send"].put(
                        {
                            "act": "name",
                            "guid": self.guid,
                            "data": random.choice(NAMES),
                        }
                    )
            elif event.get("act") == "quit":
                if not event.get("code") == 200:
                    return
                if not event.get("guid") == self.guid:
                    # 队友离开
                    p = self.findPartsFromGuid(event.get("guid"))
                    if not p:
                        return
                    part.remove(p)

            elif event.get("act") == "wait":
                if not event.get("code") == 200:
                    return
                if not event.get("guid") == self.guid:
                    # 队友取消准备
                    p = self.findPartsFromGuid(event.get("guid"))
                    if not p:
                        return
                    p["status"] = "wait"
                else:
                    cfg["act"] = "wait"
                    cfg["menu"] = [
                        "1 准备就绪",
                    ]
                    cfg["input"] = [
                        1,
                    ]
            elif event.get("act") == "ready":
                if not event.get("code") == 200:
                    return
                if not event.get("guid") == self.guid:
                    # 队友准备就绪
                    p = self.findPartsFromGuid(event.get("guid"))
                    if not p:
                        return
                    p["status"] = "ready"
                else:
                    cfg["act"] = "ready"
                    cfg["menu"] = [
                        "1 取消准备",
                    ]
                    cfg["input"] = [
                        1,
                    ]

            elif event.get("act") == "lock":
                if not event.get("code") == 200:
                    return
                cfg["act"] = "lock"
                cfg["menu"] = [
                    f'准备开始 {event.get("data")}',
                ]
                cfg["input"] = []
            elif event.get("act") == "fight":
                if not event.get("code") == 200:
                    return
                cfg["act"] = "fight"
                cfg["menu"] = None
                cfg["input"] = []
                self.level = event.get("data")
                # 创建卡片
                self.createCard()
                # 创建队友
                self.createHero()
                # 创建地形
                self.createTrack()
            elif event.get("act") == "money":
                self.money = event.get("data")
            elif event.get("act") == "newZombie":
                self.createZombie(event.get("data"))
            elif event.get("act") == "newPlant":
                zw = self.createPlant(event.get("data"))
                if event.get("guid") == self.guid:
                    self.myShop.add(zw)
            else:
                pass

    def findPartsFromGuid(self, guid):
        """查找队友"""
        for i in part:
            if i["guid"] == guid:
                return i
        else:
            return False

    def createCard(self):
        """创建卡片"""
        w = 78
        for i in range(7):
            crd = myCards(w, 10, i)
            self.cards.add(crd)
            w += 64

    def createHero(self):
        """创建队友"""
        lf = SCREEN_WIDTH - 70
        for i in part:
            hero = myHeros(lf, 0)
            hero.setData(i)
            self.heros.add(hero)
            lf -= 72

    def createTrack(self):
        """创建地形"""
        item = myItems(0, 0)
        self.tracks.add(item)
        track = myTracks(0, 88)
        self.tracks.add(track)

    def createZombie(self, data):
        """创建僵尸"""
        tool = data.get("tool")
        if tool == 1:
            zombie = FlagZombie(data)
            zombie.startMove()
        elif tool == 2:
            zombie = ConeheadZombie(data)
            zombie.startMove()
        elif tool == 3:
            zombie = BucketheadZombie(data)
            zombie.startMove()
        else:
            zombie = NormalZombie(data)
            zombie.startMove()
        self.zombies.add(zombie)

    def createPlant(self, data):
        """创建植物"""
        name = data.get("name")
        zw = eval(name)()
        zw.setData(data)
        zw.startMove()
        self.plants.add(zw)
        return zw


if __name__ == "__main__":
    print("hello")
    # 网路线程
    thread1 = mainThread(tcp)
    thread1.start()
    thread2 = MainGame()
    thread2.startGame()
    thread1.stop()
    thread1.join()
    print("bye")
